package in.muton.edushare.validators.formvalidators;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;
import org.apache.wicket.validation.IValidationError;
import org.apache.wicket.validation.ValidationError;

public class DateComparisonValidator extends AbstractFormValidator {

	private static final long serialVersionUID = 4058370935395068291L;
	private static Log log = LogFactory.getLog(DateComparisonValidator.class);
	
	private final FormComponent<?>[] formComponents;
	private boolean lowerDateNullable = false;
	private boolean higherDateNullable = false;
	
	public DateComparisonValidator(FormComponent<Date> lowerDate, FormComponent<Date> higherDate) {
		if(lowerDate == null){
			throw new IllegalStateException("Lower Date Field Cant Be NULL");
		}
		
		if(higherDate == null){
			throw new IllegalStateException("Higher Date Field Cant Be NULL");
		}
		
		formComponents = new FormComponent[]{lowerDate, higherDate};
	}

	public FormComponent<?>[] getDependentFormComponents() {
		return formComponents;
	}

	@SuppressWarnings("unchecked")
	public void validate(Form<?> form) {
		final FormComponent<Date> lowDate = (FormComponent<Date>)formComponents[0];
		final FormComponent<Date> highDate = (FormComponent<Date>)formComponents[1];
		
		log.debug("lower date: "+ lowDate.getConvertedInput()+", higher date: " + highDate.getConvertedInput());
		
		ValidationError ve = new ValidationError();
		ve.setVariables(this.variablesMap());
		ve.addMessageKey(resourceKey());
		
		//if lower date is null but is set not to be
		if(lowDate.getConvertedInput()== null && !lowerDateNullable){
			formComponents[0].error((IValidationError)ve);
		}
		
		//if higher date is null but is set not to be
		if(highDate.getConvertedInput()== null && !higherDateNullable){
			formComponents[1].error((IValidationError)ve);
		}
		
		//If lower is not null and higher is not null able
		if(lowDate.getConvertedInput()!=null && !higherDateNullable){
				if(lowDate.getConvertedInput().after(highDate.getConvertedInput())){
					log.debug("Lower date is after higher date!");
					formComponents[0].error((IValidationError)ve);
				}
		}
		
	}

	public void setHigherDateNullable(boolean higherDateNullable) {
		this.higherDateNullable = higherDateNullable;
	}

	public boolean isHigherDateNullable() {
		return higherDateNullable;
	}

	public void setLowerDateNullable(boolean lowerDateNullable) {
		this.lowerDateNullable = lowerDateNullable;
	}

	public boolean isLowerDateNullable() {
		return lowerDateNullable;
	}

}
